﻿using System;
using System.Collections.Generic;
using System.Linq;
using AMAP.Domain;
using AMAP.ServiceClasses.Common;
using AMAP.ServiceInterfaces;
using AMAP.ServiceInterfaces.Common;
using System.Text;
using System.Security.Cryptography;

namespace AMAP.ServiceClasses
{
    public class AuthenticationService : BaseRepositoryService<User>, IAuthenticationService
    {
        public AuthenticationService(IDatabaseFactory databaseFactory)
            : base(databaseFactory)
        {
        }

        public bool CheckAuthentication(string Email, string Password)
        {
            return this.dataContext.UserSet.FirstOrDefault(u => u.Email == Email.ToLower() && u.Password == Password) != null;
        }

        public bool IsEmailAvailable(string Email)
        {
            try
            {
                var l = this.dataContext.UserSet.FirstOrDefault(u => u.Email == Email.ToLower());
                return l == null;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public bool IsUserInRole(string Email, string RoleName)
        {
            try
            {
                string[] Roles = GetUserRoles(Email);
                return Roles.Contains(RoleName);
            }
            catch (Exception)
            {
                return false;
            }
        }

        public string[] GetUserRoles(string Email)
        {
            var Roles = new List<string>();

            User User = dataContext.UserSet.FirstOrDefault(u => u.Email == Email);
            if (User != null)
            {
                if (User.Client != null)
                    Roles.Add(EnumTypes.User.Client.ToString());
                else if (User.Supplier != null)
                    Roles.Add(EnumTypes.User.Supplier.ToString());
                else
                    foreach (string s in User.Volunteer.VolunteerRole.Select(r => r.Role.Name))
                        Roles.Add(s);
            }

            return Roles.ToArray<string>();
        }

        public string[] GetAllRoles()
        {
            return dataContext.RoleSet.Select(r => r.Name).ToArray<string>();
        }
    }
}
